package com.example.authority.common.handler;

import cn.hutool.json.JSONUtil;
import com.example.authority.common.entity.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@Component
public class LoginFailedHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=utf-8");
        ServletOutputStream out=response.getOutputStream();
        Result r=Result.fail(exception.getMessage());
        out.write(JSONUtil.toJsonStr(r).getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
